package com.forlove.app.qselect.friend.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.qselect.friend.adapter.FriendGroupAdapter;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.presenter.MineFriendPresenter;
import com.forlove.app.qselect.friend.view.MineFriendView;
import com.forlove.app.qselect.friend.widget.NestedExpandaleListView;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntityList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * Created by yjl on 2017/11/25.
 */

public class MineFriendActivity extends BaseActivity<MineFriendPresenter>
        implements MineFriendView, View.OnClickListener {
    private final int load_friend_cache = 10086;//加载完缓存
    @BindView(R.id.view_fade_back)
    FrameLayout view_fade_back;

    @BindView(R.id.list_friend)
    NestedExpandaleListView friendListView;

    @BindView(R.id.view_search_account)
    RelativeLayout view_search_account;

    @BindView(R.id.text_add_friends)
    TextView text_add_friends;    //添加

    @BindView(R.id.view_no_friend)
    LinearLayout view_no_friend;

    @BindView(R.id.bt_add_new_friend)
    TextView bt_add_new_friend;  //添加好友


    private View numView;
    private TextView friendnum;
    private FriendGroupAdapter friendGroupAdapter;
    private List<MineFriendEntity> friendEntities = new ArrayList<>();
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();
    private Handler cacheHandler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_firends;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new MineFriendPresenter(this);
        }
        view_search_account.setOnClickListener(this);
        text_add_friends.setOnClickListener(this);
        view_fade_back.setOnClickListener(this);
        bt_add_new_friend.setOnClickListener(this);

        numView = getLayoutInflater().inflate(R.layout.layout_mine_friend_footer, null);
        if (friendListView.getFooterViewsCount() == 0) {
            friendListView.addFooterView(numView);
        }
        friendnum = (TextView) numView.findViewById(R.id.text_show_friend_num);

        friendListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        friendGroupAdapter = new FriendGroupAdapter(this, presenter, friendEntities);
        friendListView.setAdapter(friendGroupAdapter);
//        if (friendEntities.size() > 0) {
//            showListView();
//        } else {
//            showInviteView();
//        }
        loadCache();
        presenter.loadFriendListData();
    }

    @Override
    public void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    private void loadCache() {
        if (cacheHandler == null) {
            cacheHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    //处理缓存
                    if (msg.what == load_friend_cache) {
                        if (friendGroupAdapter != null) {
//                            friendGroupAdapter.updateFriendList(friendEntities);
                            if (friendEntities.size() > 0) {
                                showListView();
                                friendGroupAdapter.notifyDataSetChanged();//会保存刷新前的状态，比如Listview滑动的位置；
                            } else {
                                showInviteView();
                            }
                        }
                    }
                    return false;
                }
            });
        }
        HandlerThread handlerThread = new HandlerThread("loadFriendCache");
        handlerThread.start();
        Handler loadHandler = new Handler(handlerThread.getLooper());
        loadHandler.post(new Runnable() {
            @Override
            public void run() {

                ContactsInfoEntityList infoEntityList = new ContactsInfoEntityList();
                infoEntityList.parseJSONString(ContactsManager.getSaveContactsFriend(MineFriendActivity.this));
                if (infoEntityList.contactsInfoEntities.size() > 0) {
                    contactsInfoEntities.clear();
                    contactsInfoEntities.addAll(infoEntityList.contactsInfoEntities);
                }
                String friendList = FriendManager.getFriendList(MineFriendActivity.this);
                if (!TextUtils.isEmpty(friendList)) {
                    try {
                        List<MineFriendEntity> mineFriendEntities = ParseHelper.getModelList(friendList,
                                "data.friends", MineFriendEntity.class);

                        if (friendEntities.size() == 0
                                && mineFriendEntities != null
                                && mineFriendEntities.size() > 0) {
                            List<MineFriendEntity> sortFriend = new ArrayList<>();
                            sortFriend.addAll(FriendManager.contactsToFriendEntity(mineFriendEntities, contactsInfoEntities));
                            Collections.sort(sortFriend);
                            friendEntities.clear();
                            friendEntities.addAll(sortFriend);
                            if (friendGroupAdapter != null) {
                                friendGroupAdapter.setContacts(contactsInfoEntities);
                                friendGroupAdapter.updateFriendList(friendEntities);
                            }
                            if (cacheHandler != null) {
                                cacheHandler.sendEmptyMessage(load_friend_cache);
                            }
                        }
                    } catch (Exception e) {
                    }

                }
            }
        });
    }

    private void showInviteView() {
        friendListView.setVisibility(View.GONE);
        view_no_friend.setVisibility(View.VISIBLE);
    }

    private void showListView() {
        if (friendGroupAdapter != null) {
            for (int i = 0; i < friendGroupAdapter.getGroupCount(); i++) {
                friendListView.expandGroup(i);
            }
        }
        friendnum.setText(friendEntities.size() + "位好友");
        view_no_friend.setVisibility(View.GONE);
        friendListView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.view_search_account:
                startActivity(new Intent(this, SearchFriendActivity.class));
                break;

            case R.id.bt_add_new_friend:
//                startActivity(new Intent(this, AddContactsFriendActivity.class));
                startActivity(new Intent(this, AddNewFriendActivity.class));
                break;
            case R.id.text_add_friends:
                startActivity(new Intent(this, AddNewFriendActivity.class));
                break;
            case R.id.view_fade_back:
                onBackPressed();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cacheHandler = null;
    }

    @Override
    public void updateFriendListView(List<MineFriendEntity> friendEntities) {
        this.friendEntities.clear();
        List<MineFriendEntity> sortFriend = new ArrayList<>();
        if (friendEntities != null) {
            sortFriend.addAll(FriendManager.contactsToFriendEntity(friendEntities, contactsInfoEntities));
            Collections.sort(sortFriend);
        }
        this.friendEntities.addAll(sortFriend);
        friendGroupAdapter.updateFriendList(this.friendEntities);
        if (friendEntities.size() > 0) {
            showListView();
            friendGroupAdapter.notifyDataSetChanged();//会保存刷新前的状态，比如Listview滑动的位置；
        } else {
            showInviteView();
        }
    }
    
}
